##============================================================================##
## You need the following if this is ever being run as a script.
import os, sys  
sys.path.insert(0, "C:\Documents and Settings\wendy_admin\src\eclipse_workspace\djangodb\main")  
if not os.environ.has_key("DJANGO_SETTINGS_MODULE"):
    os.environ["DJANGO_SETTINGS_MODULE"]="formstates_wjContact.settings"
##============================================================================##

    
import datetime
import pdb

from django import newforms as forms
from django.newforms.forms import SortedDictFromList

## This is for the check_for_duplicates method. Should consider refactoring
## this, to keep views type stuff out of this forms file.
from django.shortcuts import render_to_response

from formstates_wjContact.constants import MSG_CODES, DEFAULT_LISTSIZE

## Core cbv field-related stuff
from formstates_wjContact.views.fields import FieldList 


##==============================================================================

class AbstractExtensibleFormState(object):
    """  """

    def __init__(self):
        """  """
        pass      

    def setup(self, the_form):
        pass
       
       
##==============================================================================

class ExtensibleFormFreshEditState(object):
    """  """

    def __init__(self):
        """  """
        pass      

    def setup(self, the_form):
        owner = the_form.main_object
        ## Since this is an edit_form, we need to get out the existing database
        ## records and display them. Thus far we have the database ids for 
        ## the 'main entity' that this form is about (Contact, Owner, 
        ## whatever)
        ## Get out the names and values of the model fields, and put them 
        ## into our kwargs with the key 'data'. When we go through the 
        ## __init__
        ## from the superclass, these will become the data variable passed
        ## in to create a Bound form.
        model_fieldnames = [field.name for field in owner._meta.fields]
        model_fieldvalues = [owner.__getattribute__(fieldname) for 
        fieldname in model_fieldnames]      
        data_dict=dict(zip(model_fieldnames, model_fieldvalues))
        kwargs['initial'] = data_dict
        args = ()
        return (args, kwargs)
       
                  
    def build_repeaters(self, the_form):        
        """Subclasses will implement """
        """ Or if not using subclasses to implement, try using
            form.initial as a whole rather than populating the individual 
            fields perhaps?"""
        ## If we are 'fresh', we need to get the relevant data out of the 
        ## database, then build the appropriate 'field' object for each 
        ## one.
        ## First get the needed data out of the database
        ## Then build-up the fieldlists inside the field-sequences
        fields=[]
        for dummy, fieldlist in the_form.fieldlists:
            fk_fieldname = fieldlist.fk_fieldname
            model = fieldlist.model_class
            kwargs={fk_fieldname+'__exact': the_form.main_object}
            bits=model.objects.filter(**kwargs)
                
            for i, bit in enumerate(bits): 
                for attr in fieldlist.template_field.widget.database_to_widget.keys():
                    value = bit.__getattribute__(attr)            
                    fieldname = fieldlist.base_name + '_%s' % (i+1)     
                    value_fieldname=fieldlist.template_field.widget.widget_to_database[fieldlist.template_field.widget.database_to_widget[attr]]
                    the_form.initial[value_fieldname % fieldname] = value                              

            how_many=len(the_form.get_names_from_datadict(fieldlist.base_name))
            fieldlist.build_fields(how_many)
            ## Also give each one a reference to the form  they are on, so
            ## that when they are needing to Bind, they can do so.
            fieldlist.set_form(the_form) 
            pluralised_fieldname = fieldlist.base_name + 's'
            the_form.__setattr__(pluralised_fieldname, fieldlist)        
            ## And then deal with getting them all into self.fields  
            the_form.put_fieldlists_into_form_fields()      
##==============================================================================

class ExtensibleFormTouchedEditState(object):
    """  """

    def __init__(self):
        """  """
        pass      

    def setup(self, the_form):
        ## Don't need to do anything, I think - we have the data we need
        ## in  our args (from request.POST), and when we later go to save()
        ## we have a self.name_id also.
        kwargs = {}
        args = ()
        return (args, kwargs)
                      
    def build_repeaters(self, the_form):        
        ## first build-up the fieldlists inside the field-sequences
        for dummy, fieldlist in the_form.fieldlists:
            ## fs will be a tuple of (name, FieldList) ie
            ## ('pets', 
            ## <wjContact.contacts.views.fields.FieldList object at 0x016218B0>)              
            ## base_name is the 'base name' for this recurring field, ie 
            ## phone for phones, pet for pets, etc                
            how_many=len(the_form.get_names_from_datadict(fieldlist.base_name))
            fieldlist.build_fields(how_many)
            ## Also give each one a reference to the form  they are on, so
            ## that when they are needing to Bind, they can do so.
            fieldlist.set_form(the_form)  
        ## And then deal with getting them all into self.fields  
        the_form.put_fieldlists_into_form_fields()      
           
##============================================================================##
class ExtensibleFormFreshAddState(object):
    """  """

    def __init__(self):
        """  """
        pass      

    def setup(self, the_form):
        ## We currently do nothing for fresh_add forms - but here is a hook
        ## where we could if we wanted - ie if we wanted to change the 
        ## default values displayed or something.
        kwargs = {}
        args = ()
        return (args, kwargs)
             
                  
    def build_repeaters(self, the_form):
        """Can combine this with one of the other conditionals """ 
        ## first build-up the fieldlists inside the field-sequences
        for dummy, fieldlist in the_form.fieldlists:
            ## fs will be a tuple of (name, FieldList) ie
            ## ('pets', 
            ## <wjContact.contacts.views.fields.FieldList object at 0x016218B0>)
            fieldlist.build_fields(number=1)
            ## Also give each one a reference to the formn  they are on, so
            ## that when they are needing to Bind, they can
            fieldlist.set_form(the_form)   
        ## And then deal with getting them all into self.fields 
        the_form.put_fieldlists_into_form_fields()      


##============================================================================##
class ExtensibleFormTouchedAddState(object):
    """  """
    def __init__(self):
        """  """
        pass      

    def setup(self, the_form):
        ## We currently do nothing for touched_add forms - all the 
        ## necessary data is in args already, but here is a 
        ## hook where we could if we wanted.
        kwargs = {}
        args = ()
        return (args, kwargs)
       
                  
    def build_repeaters(self, the_form): 
        ## first build-up the fieldlists inside the field-sequences
        for dummy, fieldlist in the_form.fieldlists:
            ## fs will be a tuple of (name, FieldList) ie
            ## ('pets', 
            ## <wjContact.contacts.views.fields.FieldList object at 0x016218B0>)              
            ## base_name is the 'base name' for this recurring field, ie 
            ## phone for phones, pet for pets, etc      
            how_many=len(the_form.get_names_from_datadict(fieldlist.base_name))
            fieldlist.build_fields(how_many)
            ## Also give each one a reference to the form  they are on, so
            ## that when they are needing to Bind, they can do so.
            fieldlist.set_form(the_form)  

        ## And then deal with getting them all into self.fields  
        the_form.put_fieldlists_into_form_fields()      
           

##============================================================================##
class ExtensibleFormTouchedInitialisedAddState(object):
    """  """
    def __init__(self):
        """  """
        pass      

    def setup(self, the_form):
        kwargs = {}
        args = ()
        return (args, kwargs)
       
                  
    def build_repeaters(self, the_form):
        """Can combine this with one of the other conditionals """ 
        ## first build-up the fieldlists inside the field-sequences         
        for dummy, fieldlist in the_form.fieldlists:
            ## fs will be a tuple of (name, FieldList) ie
            ## ('pets', 
            ## <wjContact.contacts.views.fields.FieldList object at 0x016218B0>)              
            ## base_name is the 'base name' for this recurring field, ie 
            ## phone for phones, pet for pets, etc                
            how_many=len(the_form.get_names_from_datadict(fieldlist.base_name))
            fieldlist.build_fields(how_many)
            ## Also give each one a reference to the form  they are on, so
            ## that when they are needing to Bind, they can do so.
            fieldlist.set_form(the_form)  
               
        ## And then deal with getting them all into self.fields 
        the_form.put_fieldlists_into_form_fields()       
                    
##============================================================================##
class ExtensibleFormTouchedInitialiedEditState(object):
    """  """
    def __init__(self):
        """  """
        pass      

    def setup(self, the_form):
        kwargs = {}
        args = ()
        return (args, kwargs)
                      
    def build_repeaters(self, the_form):
        """Can combine this with one of the other conditionals """ 
        ## first build-up the fieldlists inside the field-sequences         
        for dummy, fieldlist in the_form.fieldlists:
            ## fs will be a tuple of (name, FieldList) ie
            ## ('pets', 
            ## <wjContact.contacts.views.fields.FieldList object at 0x016218B0>)              
            ## base_name is the 'base name' for this recurring field, ie 
            ## phone for phones, pet for pets, etc                
            how_many=len(the_form.get_names_from_datadict(fieldlist.base_name))
            fieldlist.build_fields(how_many)
            ## Also give each one a reference to the form  they are on, so
            ## that when they are needing to Bind, they can do so.
            fieldlist.set_form(the_form)  
               
        ## And then deal with getting them all into self.fields 
        the_form.put_fieldlists_into_form_fields()       
            



        

